今天是紀錄LeetCode解題的第八天
第八題題目:Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer.
The algorithm for myAtoi(string s) is as follows:
實作myAtoi(string s)將字串轉換成32位元有號整數
演算法如下:
class Solution:
def myAtoi(self, s: str) -> int:
s = s.lstrip() #去掉前導空白
if not s:
return 0
#處理正負號
sign = 1
if s[0] == '+' or s[0] == '-':
if s[0] == '-':
sign = -1
s = s[1:]
#開始讀數字
num = 0
for c in s:
if not c.isdigit():
break
num = num * 10 + int(c)
# 檢查是否超過範圍
if sign == 1 and num >= 2**31 - 1:
return 2**31 - 1
if sign == -1 and num >= 2**31:
return -2**31
return sign * num